<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RustCloud 监控仪表板</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }

        .nav {
            background: white;
            padding: 15px 0;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .nav ul {
            list-style: none;
            display: flex;
            gap: 30px;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .nav a:hover, .nav a.active {
            background-color: #667eea;
            color: white;
        }

        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }

        .card h3 {
            font-size: 18px;
            margin-bottom: 15px;
            color: #667eea;
        }

        .metric-value {
            font-size: 36px;
            font-weight: bold;
            margin: 10px 0;
        }

        .metric-label {
            color: #666;
            font-size: 14px;
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-healthy { background-color: #10b981; }
        .status-warning { background-color: #f59e0b; }
        .status-error { background-color: #ef4444; }
        .status-critical { background-color: #dc2626; }

        .chart-container {
            height: 200px;
            margin: 15px 0;
            background: #f8f9fa;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
        }

        .alert-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .alert-item {
            padding: 10px;
            margin: 5px 0;
            border-left: 4px solid #ccc;
            background: #f8f9fa;
            border-radius: 0 5px 5px 0;
        }

        .alert-critical { border-left-color: #dc2626; }
        .alert-error { border-left-color: #ef4444; }
        .alert-warning { border-left-color: #f59e0b; }
        .alert-info { border-left-color: #3b82f6; }

        .refresh-indicator {
            float: right;
            color: #666;
            font-size: 12px;
        }

        .loading {
            opacity: 0.6;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .loading .metric-value {
            animation: pulse 1.5s ease-in-out infinite;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="container">
            <h1>🦀 RustCloud 监控仪表板</h1>
        </div>
    </header>

    <nav class="nav">
        <div class="container">
            <ul>
                <li><a href="/" class="active">概览</a></li>
                <li><a href="/metrics">指标</a></li>
                <li><a href="/alerts">告警</a></li>
                <li><a href="/apm">APM</a></li>
                <li><a href="/health">健康检查</a></li>
            </ul>
        </div>
    </nav>

    <main class="container">
        <div class="dashboard-grid">
            <!-- 系统状态 -->
            <div class="card">
                <h3>系统状态</h3>
                <div class="metric-value" id="system-status">
                    <span class="status-indicator status-healthy"></span>
                    健康
                </div>
                <div class="metric-label">当前系统运行状态</div>
            </div>

            <!-- 活跃服务 -->
            <div class="card">
                <h3>活跃服务</h3>
                <div class="metric-value" id="active-services">-</div>
                <div class="metric-label">当前运行的服务数量</div>
            </div>

            <!-- 总指标数 -->
            <div class="card">
                <h3>监控指标</h3>
                <div class="metric-value" id="total-metrics">-</div>
                <div class="metric-label">系统收集的指标总数</div>
            </div>

            <!-- 活跃告警 -->
            <div class="card">
                <h3>活跃告警</h3>
                <div class="metric-value" id="active-alerts">-</div>
                <div class="metric-label">需要关注的告警数量</div>
            </div>

            <!-- 平均响应时间 -->
            <div class="card">
                <h3>平均响应时间</h3>
                <div class="metric-value" id="avg-response-time">-</div>
                <div class="metric-label">毫秒 (ms)</div>
            </div>

            <!-- 错误率 -->
            <div class="card">
                <h3>错误率</h3>
                <div class="metric-value" id="error-rate">-</div>
                <div class="metric-label">百分比 (%)</div>
            </div>
        </div>

        <!-- 性能趋势图 -->
        <div class="card">
            <h3>性能趋势 <span class="refresh-indicator" id="last-update">更新中...</span></h3>
            <div class="chart-container">
                📊 实时性能图表 (待实现)
            </div>
        </div>

        <!-- 最新告警 -->
        <div class="card">
            <h3>最新告警</h3>
            <div class="alert-list" id="recent-alerts">
                <div class="alert-item alert-info">
                    📡 系统正在加载告警数据...
                </div>
            </div>
        </div>
    </main>

    <script>
        // 自动刷新数据
        let refreshInterval;
        const REFRESH_RATE = 5000; // 5秒

        // 获取概览数据
        async function fetchOverview() {
            try {
                const response = await fetch('/api/overview');
                const result = await response.json();
                
                if (result.success) {
                    updateOverview(result.data);
                } else {
                    console.error('获取概览数据失败:', result.error);
                }
            } catch (error) {
                console.error('网络错误:', error);
                showError('无法连接到服务器');
            }
        }

        // 更新概览数据
        function updateOverview(data) {
            // 移除加载状态
            document.body.classList.remove('loading');

            // 更新系统状态
            const statusElement = document.getElementById('system-status');
            const statusIndicator = statusElement.querySelector('.status-indicator');
            statusIndicator.className = 'status-indicator status-' + data.system_status.toLowerCase();
            statusElement.innerHTML = `<span class="status-indicator status-${data.system_status.toLowerCase()}"></span>${data.system_status}`;

            // 更新数值
            document.getElementById('active-services').textContent = data.active_services;
            document.getElementById('total-metrics').textContent = data.total_metrics;
            document.getElementById('active-alerts').textContent = data.active_alerts;
            document.getElementById('avg-response-time').textContent = data.avg_response_time.toFixed(2);
            document.getElementById('error-rate').textContent = data.error_rate.toFixed(2);

            // 更新最后刷新时间
            document.getElementById('last-update').textContent = `最后更新: ${new Date().toLocaleTimeString()}`;
        }

        // 获取告警数据
        async function fetchAlerts() {
            try {
                const response = await fetch('/api/alerts');
                const result = await response.json();
                
                if (result.success) {
                    updateAlerts(result.data);
                }
            } catch (error) {
                console.error('获取告警数据失败:', error);
            }
        }

        // 更新告警列表
        function updateAlerts(alerts) {
            const alertsList = document.getElementById('recent-alerts');
            
            if (alerts.length === 0) {
                alertsList.innerHTML = '<div class="alert-item alert-info">✅ 暂无活跃告警</div>';
                return;
            }

            alertsList.innerHTML = alerts.slice(0, 5).map(alert => {
                const severityClass = 'alert-' + alert.severity.toLowerCase();
                const timeAgo = new Date(alert.fired_at).toLocaleString();
                return `
                    <div class="alert-item ${severityClass}">
                        <strong>${alert.name}</strong><br>
                        <small>${alert.annotations.description || '无描述'} - ${timeAgo}</small>
                    </div>
                `;
            }).join('');
        }

        // 显示错误信息
        function showError(message) {
            const alertsList = document.getElementById('recent-alerts');
            alertsList.innerHTML = `<div class="alert-item alert-error">❌ ${message}</div>`;
        }

        // 启动自动刷新
        function startAutoRefresh() {
            // 立即加载一次数据
            document.body.classList.add('loading');
            fetchOverview();
            fetchAlerts();

            // 设置定时刷新
            refreshInterval = setInterval(() => {
                fetchOverview();
                fetchAlerts();
            }, REFRESH_RATE);
        }

        // 停止自动刷新
        function stopAutoRefresh() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        }

        // 页面加载完成后启动
        document.addEventListener('DOMContentLoaded', startAutoRefresh);

        // 页面隐藏时停止刷新，显示时恢复
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                stopAutoRefresh();
            } else {
                startAutoRefresh();
            }
        });

        // 页面卸载时清理
        window.addEventListener('beforeunload', stopAutoRefresh);
    </script>
</body>
</html>